<template>
  <div v-if="userStore.isAuthenticated" class="token-status">
    <!-- Token状态指示器 -->
    <div class="flex items-center space-x-2 text-xs">
      <div 
        :class="[
          'w-2 h-2 rounded-full',
          tokenStatusColor
        ]"
      ></div>
      <span :class="['text-glass-text-muted', { 'text-orange-500': isExpiringSoon, 'text-red-500': remainingMinutes <= 5 }]">
        {{ tokenStatusText }}
      </span>
    </div>
    
    <!-- 刷新按钮（仅在即将过期时显示） -->
    <button 
      v-if="isExpiringSoon && userStore.tokenData?.refreshToken"
      @click="handleRefreshToken"
      :disabled="isRefreshing"
      class="ml-2 text-xs glass-button px-2 py-1 rounded transition-colors"
    >
      <i v-if="isRefreshing" class="fas fa-spinner fa-spin"></i>
      <i v-else class="fas fa-sync-alt"></i>
      {{ isRefreshing ? '刷新中...' : '刷新' }}
    </button>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { formatRemainingTime } from '@/utils/tokenManager'

const userStore = useUserStore()
const isRefreshing = ref(false)

// 计算剩余时间
const remainingMinutes = computed(() => userStore.getTokenRemainingTime())

// 是否即将过期
const isExpiringSoon = computed(() => userStore.isTokenExpiringSoon(30))

// Token状态颜色
const tokenStatusColor = computed(() => {
  const minutes = remainingMinutes.value
  if (minutes <= 5) return 'bg-red-500'
  if (minutes <= 30) return 'bg-orange-500'
  return 'bg-green-500'
})

// Token状态文本
const tokenStatusText = computed(() => {
  const minutes = remainingMinutes.value
  if (minutes <= 0) return 'Session已过期'
  if (minutes <= 5) return `即将过期: ${formatRemainingTime(minutes)}`
  if (minutes <= 30) return `${formatRemainingTime(minutes)}后过期`
  return `Session有效: ${formatRemainingTime(minutes)}`
})

// 处理刷新token
const handleRefreshToken = async () => {
  isRefreshing.value = true
  try {
    await userStore.refreshToken()
  } catch (error) {
    console.error('刷新token失败:', error)
  } finally {
    isRefreshing.value = false
  }
}

// 定时更新状态
let updateInterval: number | null = null

onMounted(() => {
  // 每分钟更新一次状态
  updateInterval = window.setInterval(() => {
    // 触发重新计算
    userStore.getTokenRemainingTime()
  }, 60 * 1000)
})

onUnmounted(() => {
  if (updateInterval) {
    clearInterval(updateInterval)
  }
})
</script>

<style scoped>
.token-status {
  @apply flex items-center;
}

.glass-button {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.glass-button:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.95);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.text-glass-text-muted {
  color: rgba(31, 41, 55, 0.7);
}
</style>
